import os

def getDocsFromDirectory(strDirname):
	import os
	astrFiles = os.listdir(strDirname)
	ret = []
	for strFile in astrFiles:
		if not strFile.endswith('.py') or strFile.endswith('*.pyw'): continue
		docs = getDocsFromSource(os.path.join(strDirname, strFile))
		ret.append(docs)
		
	return ret
	

def getDocsFromSource(strFilename):
	doc = Documentation()
	doc.module = strFilename.replace('.pyw','').replace('.py','')
	doc.filename = os.path.split( strFilename)[1] #note file "name", not path.
	
	f = open(strFilename)
	src = f.read().replace('\r\n','\n').split('\n')
	f.close()
	
	i=0
	while i < len(src):
		line = src[i]
		
		if False: #line.startswith('class'):
			# We are basically making the assumption of one class per file here...
			pass
		elif line.startswith('def') or line.startswith('\tdef') or line.startswith('    def'):
			if line.startswith('def'): type = 'functions'
			else: type = 'methods'
			strPrototype = line
			
			if ':' not in line:
				end = min(i+4, len(src))
				j = i+1
				while j < end:
					strPrototype += ' '+src[j]
					if ':' in line: break
					j+=1
				i = j
			strPrototype = strPrototype.strip().rstrip(':').replace('def ','')
			if type=='methods': strPrototype = strPrototype.replace('self,','').replace('self ,','').replace('(self)','()').replace('(self', '(') 
			name = strPrototype.split('(')[0].split()[0]
			i+=1
			line = src[i]
			docstr = line
			if line.strip().startswith("'''"): endstr = "'''"
			elif line.strip().startswith('"""'): endstr = '"""'
			else: endstr = None
			if endstr:
				if endstr not in line and line.strip().endswith(endstr):
					docstr = line
					j = i+1
					end = min(j+40, len(src))
					
					while j < end:
						docstr += ' '+src[j]
						if endstr in line: break
						j+=1
				docstr = docstr.replace(endstr, '')
			else:
				docstr = ''
			doc.data[type].append((name, strPrototype, docstr))
		elif line.strip()=='Properties:':
			i+=1
			import re
			regex = re.compile(r'\*([^*\r\n]+)\*\W+-\W+([^\r\n]+)')
			while True:
				line = src[i].strip()
				result = regex.match(line) 
				if result:
					doc.data['properties'].append((result.group(1),'', result.group(2)))
				if '"""' in src[i]: break
				i+=1
			
		else:
			i+=1
	
	def r(s):
		if s[0].startswith('__init'): return s[0].replace('_','aaaa',1)
		elif s[0].startswith('_'): return s[0].replace('_','z',1)
		return s[0]
	for type in 'methods', 'functions','properties','members':
		doc.data[type].sort(key=r)
	
	return doc

class Documentation:
	data = None
	module = None
	filename = None
	def __init__(self):
		self.data = {
		'methods': [], 'functions': [],'properties': [],'members': []
		}
	

	# Name, Prototype, Docstring